package com.gsk.europepharma.salesReport.struts.actions;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRCartoContourDAO;
import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;
import com.gsk.europepharma.salesReport.utils.CreateCarto;
import com.gsk.europepharma.salesReport.utils.UtilsSalesReport;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
 * Affichage de la carto de gauche.
 */
public class CartoRegion extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		try {
			// Variables de session
			HttpSession sessionObject = request.getSession();
			Integer cs_adm_pdt = (Integer) sessionObject.getAttribute("cs_adm_pdt");
			Integer cs_adm_rgpt = (Integer) sessionObject.getAttribute("cs_adm_rgpt");
			Integer cs_adm_prstn = (Integer) sessionObject.getAttribute("cs_adm_prstn");
			Integer cs_network = (Integer) sessionObject.getAttribute("cs_network");
			Integer cs_month = (Integer) sessionObject.getAttribute("cs_month");
			// Fin de session 
					
			// Recuperation des parametres
			String idGeog = request.getParameter("idGeog");
			Integer idGeogInteger = Integer.parseInt(idGeog);
			String nivGeog = request.getParameter("nivGeog"); 
			String typeImage = request.getParameter("typeImage"); 
			
			String calculPalettes = request.getParameter("calculPalettes");
			
			String source = request.getParameter("source");
			Integer CS_SRC = Integer.parseInt(source);
			String unite = request.getParameter("unite");
			String periode = request.getParameter("periode");
			
			String indicateur = request.getParameter("indicateur");
			String indicateur1 = request.getParameter("indicateur1");
			String indicateur2 = request.getParameter("indicateur2");
			
			String libGeogCartoR = "";
			String idGeogCartoR = "";
			String nivGeogCartoR = "";
			
			tbSpBoSRCartoContourDAO cartoDAO = new tbSpBoSRCartoContourDAO();
			
			Session session = cartoDAO.getSession();
			
			Query req;
			
			String strReq = "";
			
			if (!indicateur.equals("")) {
				if (nivGeog.equals("Zone")) {
					strReq = cartoDAO.QUERY_DESSINE_CARTE1_ZONE;
				} else {
					strReq = cartoDAO.QUERY_DESSINE_CARTE1_REGION;
				}
			} else {
				if (nivGeog.equals("Zone")) {
					strReq = cartoDAO.QUERY_DESSINE_CARTE1_ZONE;
				} else if (nivGeog.equals("Region")) {
					strReq = cartoDAO.QUERY_DESSINE_CARTE1_REGION;
				} else {
					strReq = cartoDAO.QUERY_DESSINE_CARTE2_SECTEUR;
				}
			}
			
			req = session.getNamedQuery(strReq);
			req.setInteger("idGeog", idGeogInteger);
			req.setString("nivGeog", nivGeog);
			req.setInteger("cs_network", cs_network);
			ArrayList result = new ArrayList(req.list());
			Iterator iter = result.iterator();
			JSONArray jsonArrayPixels = new JSONArray();
			
			Integer xmin = 4000;
			Integer xmax = 0;
			Integer ymin = 4000;
			Integer ymax = 0;
			
			while (iter.hasNext()) {
				Object[] tmp = (Object[]) iter.next();
				JSONObject pixel = new JSONObject(); 
				pixel.put("x", tmp[0]);
				pixel.put("y", tmp[1]);
				pixel.put("color", Integer.parseInt(tmp[2].toString()));
				jsonArrayPixels.add(pixel);
				if (tmp[0] != null) {
					xmin = Math.min(xmin, Integer.parseInt(tmp[0].toString()));
					xmax = Math.max(xmax, Integer.parseInt(tmp[0].toString()));
				}
				if (tmp[1] != null) {
					ymin = Math.min(ymin, Integer.parseInt(tmp[1].toString()));
					ymax = Math.max(ymax, Integer.parseInt(tmp[1].toString()));
				}
				idGeogCartoR = tmp[3].toString();
				libGeogCartoR = tmp[4].toString();
				if (tmp[5].toString().equals("Z")) {
					nivGeogCartoR = "Zone";
				} else if (tmp[5].toString().equals("R")) {
					nivGeogCartoR = "Region";
				} else if (tmp[5].toString().equals("S")) {
					nivGeogCartoR = "Secteur";
				}
			}
			
			// Ensemble des points pour le remplissage
			cartoDAO = new tbSpBoSRCartoContourDAO();
			session = cartoDAO.getSession();
			
			if (!indicateur.equals("")) { // HIERARCHIQUE 
				strReq = cartoDAO.QUERY_REMPLIR_CARTE1;
			} else { // ISOGEOG 
				if (nivGeog.equals("Zone") || nivGeog.equals("Region")) {
					strReq = cartoDAO.QUERY_REMPLIR_CARTE1;
				} else {
					strReq = cartoDAO.QUERY_REMPLIR_CARTE2_SECTEUR;
				}
			}
			req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());
			
			if (!indicateur.equals("")) { // HIERARCHIQUE 
				req.setString("indicateur", indicateur);
			} else { // ISOGEOG 
				req.setString("indicateur", indicateur1);
			}
			req.setString("data", unite + periode);	
			req.setInteger("cs_adm_pdt", cs_adm_pdt);
			req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
			req.setInteger("cs_adm_prstn", cs_adm_prstn);
			req.setInteger("CS_SRC", CS_SRC);
			req.setInteger("cs_month", cs_month);
			req.setInteger("cs_network", cs_network);
			req.setInteger("idGeog", idGeogInteger);
			req.setString("nivGeog", nivGeog);
			
			result = new ArrayList(req.list());
			iter = result.iterator();
			JSONArray jsonArrayPixelsPm = new JSONArray();
			
			while (iter.hasNext()) {
				Object[] tmp = (Object[]) iter.next();
				JSONObject pixel = new JSONObject(); 
				pixel.put("x", tmp[0]);
				pixel.put("y", tmp[1]);
				if (tmp[2] != null) {
					pixel.put("val", tmp[2]);
				} else {
					pixel.put("val", 0.0); 
				}
				pixel.put("niveau", tmp[3]);
				jsonArrayPixelsPm.add(pixel);
			}
			
			BufferedImage bufferedImage = CreateCarto.createCarto(jsonArrayPixels, xmin, ymin, xmax, ymax, jsonArrayPixelsPm, request, "Region");
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(bufferedImage, typeImage, baos);
			String encodedImage = Base64.encode(baos.toByteArray());
	        response.reset();
	        response.setHeader("Content-Type", "image/" + typeImage);
	        response.getOutputStream().write(encodedImage.getBytes("UTF-8"));
	        response.getOutputStream().flush();
	        
	        // Mise en session 
	        if (idGeogCartoR != null && !idGeogCartoR.equals("") 
	        		&& nivGeogCartoR != null && !nivGeogCartoR.equals("")
	        		&& libGeogCartoR != null && !libGeogCartoR.equals("")) {
	        	sessionObject.setAttribute("libGeogCartoR", libGeogCartoR);
	        	sessionObject.setAttribute("idGeogCartoR", idGeogCartoR);
	        	sessionObject.setAttribute("nivGeogCartoR", nivGeogCartoR);
	        }
	        
	        // Calcul du PM et deltaPM 
	        tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
			session = salesDAO.getSession();
			strReq = salesDAO.QUERY_RECUP_SALES;
			req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());
			req.setString("data", unite + periode);	
			req.setInteger("cs_adm_pdt", cs_adm_pdt);
			req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
			req.setInteger("cs_adm_prstn", cs_adm_prstn);
			req.setInteger("CS_SRC", CS_SRC);
			req.setInteger("cs_network", cs_network);
			req.setInteger("cs_month", cs_month);
			req.setString("nivGeog", nivGeogCartoR); 
			req.setInteger("idGeog", Integer.parseInt(idGeogCartoR));
			
			sessionObject.setAttribute("idGeogCartoR", idGeogCartoR);
			
			req.setMaxResults(10);
			result = new ArrayList(req.list());
			iter = result.iterator();
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();
				String deltapm = UtilsSalesReport.getDeltaPm(Double.parseDouble(val[1].toString()), Double.parseDouble(val[2].toString()), Double.parseDouble(val[3].toString()), Double.parseDouble(val[4].toString()), 1) + "";
				sessionObject.setAttribute("deltapmGeogCartoR", deltapm);
				String pm = UtilsSalesReport.getPm(Double.parseDouble(val[1].toString()), Double.parseDouble(val[3].toString()), 1) + "";
				sessionObject.setAttribute("pmGeogCartoR", pm);
				String vol = UtilsSalesReport.getVol(Double.parseDouble(val[1].toString()), 0) + "";
				sessionObject.setAttribute("volGeogCartoR", vol);
				String deltavol = UtilsSalesReport.getDeltaVol(Double.parseDouble(val[1].toString()), Double.parseDouble(val[2].toString()), 0) + "";
				sessionObject.setAttribute("deltavolGeogCartoR", deltavol);
				String evol = UtilsSalesReport.getEvolVol(Double.parseDouble(val[1].toString()), Double.parseDouble(val[2].toString()), 1) + "";
				sessionObject.setAttribute("evolGeogCartoR", evol);
			}
	        
			return null;
		} catch (Exception e) {
			HashMap<String, String> hm = new HashMap<String, String>();
			hm.put("success", "error");
			JSONObject json = JSONObject.fromObject(hm);
			response.addHeader("Content-Type", "application/json");
	        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
	        response.getOutputStream().flush();
	        return null;
		}
	}

}
